#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import *

from __init__ import ViewHTML
from __init__ import ViewImage

EPUB_WORK_DIR = os.path.join( PANEO_SITE_DATA_DIR , "tmp/epub/").replace('\\','/')

import urllib
from urlparse import urlparse
import shutil
from PIL import Image
from cStringIO import StringIO

def EPubRoot():

    if os.path.exists(EPUB_WORK_DIR) :
        shutil.rmtree(EPUB_WORK_DIR)
    os.mkdir(EPUB_WORK_DIR)
    os.mkdir(EPUB_WORK_DIR + 'META-INF/')
    os.mkdir(EPUB_WORK_DIR + 'OEBPS/')
    os.mkdir(EPUB_WORK_DIR+"OEBPS/images/")
    os.mkdir(EPUB_WORK_DIR+"OEBPS/text/")
    os.mkdir(EPUB_WORK_DIR+"OEBPS/style/")
    os.mkdir(EPUB_WORK_DIR+"OEBPS/"+PANEO_SITE_DIR+"/")

    file = codecs.open(EPUB_WORK_DIR + "OEBPS/style/fixed-layout.css", "w", "utf-8")
    file.write(u'''html,body,div#container {
width: 1280px !important;
height: 1810px !important;
margin: 0;
padding: 0;
color: #333;
background: #fff;
}
''')
    file.close()

    #COMMON COPY
    shutil.copytree(PANEO_ROOT+"/../common/",EPUB_WORK_DIR+"OEBPS/common/")
    os.mkdir(EPUB_WORK_DIR+"OEBPS/"+PANEO_SITE_DIR+"/img/")
    #shutil.copytree(PANEO_SITE_DATA_DIR+"/img/",EPUB_WORK_DIR+"OEBPS/" + PANEO_SITE_DIR + "/img/")

    ##IMG COMPRESS
    imgs = glob.glob(PANEO_SITE_DATA_DIR + "/img/"+'*')
    for imgs_f in imgs:
       if os.path.isfile(imgs_f):
            fname = os.path.split(imgs_f)[1]
            ##name, ext = os.path.splitext(fname)
            #img_file = PANEO_SITE_DATA_DIR + 'img/' + fname 
            raw_img = Image.open(imgs_f) 
            x = 1280.0
            xx = raw_img.size[1]
            yy = raw_img.size[0]
            if xx > x:
                sc = float(1280.0) / float(yy)
                y = float(yy*sc)
                raw_img.thumbnail( (int(x), int(y) ), Image.ANTIALIAS )
            lf = open(EPUB_WORK_DIR+"OEBPS/"+PANEO_SITE_DIR+"/img/"+fname,'wb')
            raw_img.save(lf,raw_img.format, quality=85)
            lf.close()

    dic = sqlite3dbm.sshelve.open(PANEO_DB)
    scfg = dic.get('siteconfig')
    pages = dic.get('pages')
    fields = dic.get('fields')
    dic.close()

    #com.apple.ibooks.display-options.xml
    file = codecs.open(EPUB_WORK_DIR + "META-INF/com.apple.ibooks.display-options.xml", "w", "utf-8")
    file.write(u'''<?xml version="1.0" encoding="utf-8"?>
<display_options>
<platform name="*">
<option name="fixed-layout">true</option>
<option name="open-to-spread">false</option>
<option name="orientation-lock">none</option>
<option name="specified-fonts">true</option>
</platform>
</display_options>''')
    file.close()

    file = codecs.open(EPUB_WORK_DIR + "META-INF/container.xml", "w", "utf-8")
    file.write(u'''<?xml version="1.0"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
<rootfiles>
<rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
</rootfiles>
</container>''')
    file.close()

    opf_img ={} 
    for k,v in sorted(pages.items(),key=lambda x:int(x[1].get('IDX'))):
        c = ViewHTML()
        bs = BeautifulSoup(c.GET(k),fromEncoding="utf8")

        #IMG
        for img in bs.find_all("img"):
            src = img.get('src')
            if src.find("http") != -1:
                f = urllib.urlopen(src)
                o = urlparse(src)
                fn = o[2].replace("/","_")
                lf = open( EPUB_WORK_DIR + "OEBPS/images/"+fn,'wb')
                lf.write(f.read())
                f.close()
                lf.close()
                img["src"] = "../images/"+fn
                opf_img[fn]={"href":"images/"+fn,"type":"image/jpeg"}
            else:
                paneo_type = img.get('data-paneo-type')
                paneo_name = img.get("data-paneo-name")
                paneo_max_width = img.get("data-paneo-max-width")
                if paneo_type is not None and paneo_name is not None:
                    kk = ('img_%s_%s'%(k,paneo_name))
                    fld = fields.get(kk)
                    if fld :
                        mime = "jpeg"
                        if os.path.exists(PANEO_SITE_DATA_DIR+'img/'+kk) :
                            if fld.get('src_on') == False :
                                #if IMG_CONV :
                                #    if paneo_max_width :
                                #        img["src"] = "/img/%s/%s/" % ( k , paneo_max_width )
                                #    else:
                                #        img["src"] = "/img/" + k
                                #else:
                                img["src"] = "../" + PANEO_SITE_DIR + "/img/" + kk
                            else:
                                if fld :
                                    img["src"] = fld.get('src') 
                            g = Image.open(PANEO_SITE_DATA_DIR+"/img/"+kk) 
                            mime = g.format
                            mime = mime.lower()
                        else:
                            if fld.get('src_on') == True:
                                img["src"] = fld.get('src') 

                        img["alt"] = fld.get('alt')
                        opf_img[kk]={"href":""+PANEO_SITE_DIR+"/img/"+kk,"type":"image/"+mime}

            #ANCHOR TAG
            for a in bs.find_all('a'):
                paneo_type = a.get('data-paneo-type')
                paneo_name = a.get('data-paneo-name')
                if paneo_type is not None and paneo_name is not None:
                    kk = ('img_%s_%s'%(k,paneo_name))
                    fld = fields.get(kk)
                    if paneo_type == "link-image":
                        img = a.find("img")
                        paneo_max_width = img.get("data-paneo-max-width")
                        if fld:
                            mime = "jpeg"
                            if os.path.exists(PANEO_SITE_DATA_DIR+'img/'+kk) :
                                if fld.get('src_on') == False :
                                    #if IMG_CONV :
                                    #    if paneo_max_width :
                                    #        img["src"] = "/img/%s/%s/" % ( k , paneo_max_width )
                                    #    else:
                                    #        img["src"] = "/img/" + k
                                    #else:
                                    img["src"] = "../" + PANEO_SITE_DIR + "/img/" + kk
                                else:
                                    if fld :
                                        img["src"] = fld.get('src') 
                                g = Image.open(PANEO_SITE_DATA_DIR+"/img/"+kk) 
                                mime = g.format
                                mime = mime.lower()
                            else:
                                if fld.get('src_on') == True:
                                    img["src"] = fld.get('src') 

                            img["alt"] = fld.get('alt')
                            opf_img[kk]={"href":""+PANEO_SITE_DIR+"/img/"+kk,"type":"image/"+mime}
            
        
        ex = bs.select("nav#global")
        if ex :
            ex[0].extract()
        ex = bs.select("header")
        if ex :
            ex[0].extract()
        ex = bs.select("div#submenu")
        if ex :
            ex[0].extract()
        ex = bs.select("div#back-top")
        if ex :
            ex[0].extract()
        for s in bs.select("script"):
            s.extract()
        for s in bs.select("style"):
            s.extract()
        for s in bs.select("meta"):
            s.extract()

        xhtml_head = '''<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" xmlns:xml="http://www.w3.org/XML/1998/namespace">
'''
        html = unicode(bs.prettify())
        html = html.replace("//"+web.ctx.host + "/","../")
        html = html.replace('src="/img/','src="../'+PANEO_SITE_DIR+'/img/')
        html = html.replace("\r\n","\n")
        html = html.replace("&lt;","<")
        html = html.replace("&gt;",">")
        html = html.replace("&amp;","&")
        html = html.replace('<!DOCTYPE html>',xhtml_head)
        html = html.replace('<html lang="ja">','')
        html = html.replace("<head>",'''<head>
<meta name="viewport" content="width=1280, height=1810" />''')
        html = html.replace("</head>",'''<link rel="stylesheet" href="../style/fixed-layout.css" type="text/css" />
</head>
''')

        file = codecs.open(EPUB_WORK_DIR + "OEBPS/text/%s.html" % k, "w", "utf-8")
        file.write(html)
        file.close()

    opf_temp = PANEO_ROOT+'/_page/templates/content.opf'
    temp = Template(      filename=opf_temp, 
                          output_encoding='utf-8',
                          input_encoding='utf-8' )
    opf_xml = temp.render(  web=web,
                            scfg = scfg, 
                            pages = pages,
                            opf_img = opf_img,
                            PANEO_SITE_DIR = PANEO_SITE_DIR,
    ) 
    file = codecs.open(EPUB_WORK_DIR + "OEBPS/content.opf", "w", "utf-8")
    file.write(opf_xml.decode('utf8'))
    file.close()

    ncx_temp = PANEO_ROOT+'/_page/templates/toc.ncx'
    temp = Template(      filename=ncx_temp, 
                          output_encoding='utf-8',
                          input_encoding='utf-8' )

    ncx_xml = temp.render(  web=web,
                            scfg = scfg, 
                            pages =pages,
    ) 
    file = codecs.open(EPUB_WORK_DIR + "OEBPS/toc.ncx", "w", "utf-8")
    file.write(ncx_xml.decode('utf8'))
    file.close()

    file = codecs.open(EPUB_WORK_DIR + "mimetype", "w", "utf-8")
    file.write(u'application/epub+zip')
    file.close()


import os,zipfile
def MakeEpubZip():

    try:
        # 作成するzipファイルのフルパス
        zipfilepath = EPUB_WORK_DIR + "../paneo.epub" 
        zip_targets = []
        #META-INF
        path = EPUB_WORK_DIR + 'META-INF'
        for dirpath, dirnames, filenames in os.walk(path):
            for filename in filenames:
                filepath = os.path.join(dirpath, filename)
                arc_name = os.path.relpath(filepath, os.path.dirname(path))
                zip_targets.append((filepath, arc_name))
            for dirname in dirnames:
                filepath = os.path.join(dirpath, dirname)
                arc_name = os.path.relpath(filepath, os.path.dirname(path)) + os.path.sep
                zip_targets.append((filepath, arc_name))
        #OEBPS
        path = EPUB_WORK_DIR + 'OEBPS'
        for dirpath, dirnames, filenames in os.walk(path):
            for filename in filenames:
                filepath = os.path.join(dirpath, filename)
                arc_name = os.path.relpath(filepath, os.path.dirname(path))
                zip_targets.append((filepath, arc_name))
            for dirname in dirnames:
                filepath = os.path.join(dirpath, dirname)
                arc_name = os.path.relpath(filepath, os.path.dirname(path)) + os.path.sep
                zip_targets.append((filepath, arc_name))

        # zipファイルの作成
        zip = zipfile.ZipFile(zipfilepath, 'w')
        zip.write(EPUB_WORK_DIR+"mimetype","mimetype")
        for filepath, name in zip_targets:
            zip.write(filepath, name)
        zip.close()
    except:
        #print "Unexpected error:", sys.exc_info()[0]
        raise

class Make:

    def GET( self ):

        EPubRoot()
        MakeEpubZip()

        file = EPUB_WORK_DIR + "../paneo.epub" 
        epub = open(file,"rb").read()
        web.header("Content-Type", "application/epub+zip;")
        web.header('Content-disposition','attachment; filename=paneo.epub') 
        return epub 
